package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.config.BaiduOcrConfig;
import com.gy.controller.assistant.utils.PdfExtractUtil;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.PersonalAward;
import com.gy.entity.result.StudentAward;
import com.gy.query.PersonalAwardQuery;
import com.gy.query.StudentAwardQuery;
import com.gy.result.Result;
import com.gy.service.StudentAwardService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.StudentAwardVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/student/award")
@Api(tags = "学生获奖接口")
@CrossOrigin
public class StudentAwardController {

    @Autowired
    private StudentAwardService studentAwardService;

    @Autowired
    private PdfExtractUtil pdfExtractUtil;



    @Autowired
    private BaiduOcrConfig baiduOcrUtil;
    /**
     * 根据openid分页查看某个人的学生获奖信息
     */
    @PostMapping("/get/personal/award")
    @ApiOperation("根据openid查看某个人的学生获奖信息")
    public Result<PageVO<StudentAward>> getPapers(@RequestBody StudentAwardQuery studentAwardQuery){
        return studentAwardService.getStudentAward(studentAwardQuery);
    }

    /**
     * 根据id主键删除学生获奖
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据id主键删除学生获奖")
    public Result deleteById(@PathVariable Long id){
        return studentAwardService.removeStudentAward(id);
    }

    /**
     * 根据id主键查询学生获奖信息
     */
    @GetMapping("/getById/{id}")
    @ApiOperation("根据id主键查询学生获奖信息")
    public Result getById(@PathVariable Long id){
        return Result.success(studentAwardService.getStudentAwardById(id));
    }

    /**
     * 更改学生获奖
     */
    @PutMapping("/update")
    @ApiOperation("更改学生获奖信息")
    public Result update(@RequestBody StudentAward studentAward){
        return studentAwardService.updateStudentAward(studentAward);
    }

    /**
     * 新增学生获奖
     */
    @PostMapping("/save")
    @ApiOperation("新增学生获奖")
    public Result AddPapers(@RequestBody StudentAward studentAward){
        return studentAwardService.saveStudentAward(studentAward);
    }

    /**
     * 根据多个id查询学生获奖
     */
    @PostMapping("/getByIds")
    @ApiOperation("根据多个id查询学生获奖")
    public Result getByIds(@RequestBody Long[] ids){
        return studentAwardService.getPersonalAwardByIds(ids);
    }


    /**
     * excel批量导出
     */
    @PostMapping("/export")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_StudentAward.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("StudentAward")
                .doWrite(transformedData);
    }


    /**
     * 汇总表格中返回学生获奖信息
     */
    @GetMapping("/getStudentAwardsBySummary")
    @ApiOperation("汇总表格中返回学生获奖信息")
    public Result<List<StudentAwardVO>> getStudentAwardsBySummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }

        // 查询并选择 StudentAwardVO 中的字段
        List<StudentAward> list = studentAwardService.lambdaQuery()
                .eq(StudentAward::getUserId, userId)
                .select(
                        StudentAward::getTitle,
                        StudentAward::getAwardLevel,
                        StudentAward::getLevel,
                        StudentAward::getGrantingUnit,
                        StudentAward::getAwardTime,
                        StudentAward::getAuthorRank,
                        StudentAward::getAwardStudents
                )
                .list();

        // 将查询结果转换为 StudentAwardVO 列表
        List<StudentAwardVO> voList = list.stream()
                .map(studentAward -> StudentAwardVO.builder()
                        .title(studentAward.getTitle())
                        .awardLevel(studentAward.getAwardLevel())
                        .level(studentAward.getLevel())
                        .grantingUnit(studentAward.getGrantingUnit())
                        .awardTime(studentAward.getAwardTime())
                        .authorRank(studentAward.getAuthorRank())
                        .awardStudents(studentAward.getAwardStudents())
                        .build())
                .collect(Collectors.toList());

        return Result.success(voList);
    }

    /**
     * 接口：解析PDF，返回StudentAward实体（前端直接填充表单）
     * @param request 包含PDF服务器路径（pdfPath）
     * @return 提取后的StudentAward + 原始OCR文本（供调试）
     */
    @PostMapping("/parse")
    public Result<Map<String, Object>> parsePdfToStudentAward(@RequestBody Map<String, String> request) {
        try {
            String filePath = request.get("filePath");
            if (filePath == null || filePath.trim().isEmpty()) {
                return Result.error("图片路径（filePath）不能为空");
            }

            // 1. 提取OCR文本（原有逻辑不变）
            String ocrText = pdfExtractUtil.extractPdfTextFromImages(filePath, baiduOcrUtil);

            // 2. 核心：用AI提取表单字段（替换原 awardExtractUtil.extractToStudentAward(ocrText)）
            StudentAward studentAward = pdfExtractUtil.extractStudentAwardByAi(ocrText);

            // 3. 返回结果（与原有一致，前端无感知）
            return Result.success(Map.of(
                    "studentAward", studentAward,
                    "rawText", ocrText
            ));

        } catch (Exception e) {
            log.error("PDF图片解析失败", e);
            return Result.error("解析失败：" + e.getMessage());
        }
    }

}
